<template>
  <div class="component-upload-image">
    <el-upload
      multiple
      :action="uploadImgUrl"
      list-type="picture-card"
      :on-success="handleUploadSuccess"
      :on-progress="handleUploadProgress"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-preview="handlePreventDefault"
      name="file"
      ref="imageUpload"
      :on-remove="handleDelete"
      :show-file-list="true"
      :headers="headers"
      :file-list="fileList"
      :class="{hide: this.fileList.length >= this.limit}"
    >
      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{file}" @click.stop>
        <img
          class="el-upload-list__item-thumbnail"
          :src="file.url" 
          alt=""
          @click.stop
        >
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click.stop="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span
            class="el-upload-list__item-delete"
            @click.stop="handleDownload(file)"
          >
            <i class="el-icon-download"></i>
          </span>
          <span
            class="el-upload-list__item-delete"
            @click.stop="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>

    <!-- 上传提示 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      title="图片预览"
      width="800px"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
       type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/minio/upload", // 使用 MinIO 上传
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      isUploading: false  // 添加上传标志，防止 watch 循环触发
    };
  },
  watch: {
    value: {
      handler(val) {
        // 如果正在上传中，跳过 watch 更新，避免闪烁
        if (this.isUploading) {
          console.log('⏸️ 正在上传中，跳过 watch 更新');
          return;
        }
        
        console.log('👀 ImageUpload watch - 接收到的值：', val);
        
        // 比较新旧值，如果相同则不更新，避免闪烁
        const currentString = this.listToString(this.fileList);
        if (currentString === val) {
          console.log('🔄 值未变化，跳过更新');
          return;
        }
        
        if (val) {
          // 首先将值转为数组（逗号分隔）
          const list = Array.isArray(val) ? val : this.value.split(',');
          console.log('📦 转换为数组：', list);
          
          // 然后将数组转为对象数组（已经是完整URL，直接使用）
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              // 直接使用完整URL，不再添加 baseUrl
              item = { name: item, url: item };
            }
            return item;
          });
          console.log('🎨 最终的 fileList：', this.fileList);
        } else {
          console.log('🔄 value 为空，清空 fileList');
          this.fileList = [];
          return [];
        }
      },
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      // 设置上传标志，防止 watch 触发导致闪烁
      this.isUploading = true;
      this.number++;
    },
    // 上传进度（ElementUI 会自动显示进度条）
    handleUploadProgress(event, file) {
      // 进度条会自动显示在图片卡片中央
      console.log(`📊 上传进度: ${file.name} - ${Math.round(event.percent)}%`);
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      console.log('📤 文件上传成功，后端响应：', res);
      console.log('📁 上传的文件名：', res.fileName);
      console.log('🔗 文件URL（完整）：', res.url);
      
      if (res.code === 200) {
        // 使用完整URL（http://localhost:8080/...）
        this.uploadList.push({ name: res.url, url: res.url });
        console.log('➕ 添加到 uploadList（使用完整URL）：', this.uploadList);
        console.log('📊 当前进度：', this.uploadList.length, '/', this.number);
        
        // 显示明显的成功提示（使用通知）
        this.$notify({
          title: '上传成功',
          message: `文件 "${file.name}" 已成功上传`,
          type: 'success',
          duration: 2000,
          position: 'top-right'
        });
        
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        // 如果所有上传都完成（包括失败的），重置上传标志
        if (this.number === 0) {
          this.isUploading = false;
        }
        this.uploadedSuccessfully();
      }
    },
    // 删除图片
    handleDelete(file) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.fileList.splice(findex, 1);
        this.$emit("input", this.listToString(this.fileList));
      }
    },
    // 删除图片（自定义slot调用）
    handleRemove(file) {
      this.handleDelete(file);
    },
    // 阻止默认预览行为（防止弹窗闪现）
    handlePreventDefault(file) {
      // 不做任何操作，只是为了覆盖默认的预览行为
      // 预览功能由我们自定义的按钮 handlePictureCardPreview 来实现
    },
    // 下载图片
    handleDownload(file) {
      const link = document.createElement('a');
      link.href = file.url;
      link.download = file.name || '图片';
      link.target = '_blank';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // 显示下载成功通知
      this.$notify({
        title: '下载成功',
        message: '图片已开始下载',
        type: 'success',
        duration: 1500,
        position: 'top-right'
      });
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.number--;
      // 如果所有上传都完成（包括失败的），重置上传标志
      if (this.number === 0) {
        this.isUploading = false;
      }
    },
    // 上传结束处理
    uploadedSuccessfully() {
      console.log('🔍 检查上传进度：', this.uploadList.length, '/', this.number);
      
      if (this.number > 0 && this.uploadList.length === this.number) {
        console.log('⏱️ 上传前的 fileList：', this.fileList);
        console.log('📦 本次上传的 uploadList：', this.uploadList);
        
        // 直接在原数组上添加，避免重新赋值导致的 UI 闪烁
        this.uploadList.forEach(item => {
          this.fileList.push(item);
        });
        console.log('🔗 合并后的 fileList：', this.fileList);
        
        this.uploadList = [];
        this.number = 0;
        
        const finalString = this.listToString(this.fileList);
        console.log('✅ 所有文件上传完成');
        console.log('📋 最终文件列表：', this.fileList);
        console.log('🎯 最终拼接的URL（逗号分隔）：', finalString);
        console.log('📤 通过 $emit 发送给父组件');
        
        this.$emit("input", finalString);
        
        // 延迟较长时间重置上传标志，确保父组件更新完成
        setTimeout(() => {
          this.isUploading = false;
          console.log('🔓 重置上传标志，允许 watch 更新');
        }, 100);
      }
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        if (list[i].url) {
          // 保留完整URL，不替换 baseUrl
          strs += list[i].url + separator;
        }
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    }
  }
};
</script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
    display: none;
}

// 确保上传中的进度条可见
::v-deep .el-upload-list__item.is-uploading {
  border-color: #409eff;
  background-color: #f5f7fa;
}

// 进度条容器样式
::v-deep .el-upload-list__item .el-progress {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80% !important;
}

// 进度条样式
::v-deep .el-progress-circle {
  width: 100px !important;
  height: 100px !important;
}

// 进度百分比文字
::v-deep .el-progress__text {
  font-size: 18px !important;
  font-weight: bold;
  color: #409eff !important;
}

// 进度条圆环
::v-deep .el-progress-circle__path {
  stroke: #409eff;
  stroke-width: 6;
}

// 进度条背景圆环
::v-deep .el-progress-circle__track {
  stroke: #e4e7ed;
  stroke-width: 6;
}

// 上传成功后的状态
::v-deep .el-upload-list__item.is-success {
  border-color: #67c23a;
}

// 图片缩略图样式
::v-deep .el-upload-list__item-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

// 操作按钮遮罩层
::v-deep .el-upload-list__item-actions {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  cursor: default;
  text-align: center;
  color: #fff;
  opacity: 0;
  font-size: 20px;
  background-color: rgba(0, 0, 0, 0.5);
  transition: opacity 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

// 鼠标悬停显示操作按钮
::v-deep .el-upload-list__item:hover .el-upload-list__item-actions {
  opacity: 1;
}

// 操作按钮（预览、下载、删除）
::v-deep .el-upload-list__item-actions span {
  display: inline-block;
  cursor: pointer;
  margin: 0 8px;
  color: #fff;
  transition: transform 0.2s, color 0.2s;
}

::v-deep .el-upload-list__item-actions span:hover {
  transform: scale(1.2);
  color: #409eff;
}

// 删除按钮悬停效果
::v-deep .el-upload-list__item-actions .el-upload-list__item-delete:hover {
  color: #f56c6c;
}

// 去掉默认动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
    transition: all 0s;
}

::v-deep .el-list-enter, .el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}
</style>

